package com.example.sunsg.okhttptest.customview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.breadtrip.R;

/**
 * Created by sunsg on 16-5-27.
 */
public class TurnTableSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    private Canvas mCanvas;
    private Thread mThread;
    private boolean mIsRunning;

    /**
     * 抽奖的文字
     */
    private String[] mText = new String[]{"苹果手机", "小米手机", "乐视手机", "锤子手机", "华为手机", "恭喜发财"};
    /**
     * 每个盘块的颜色
     */
    private int[] mColors = new int[]{0xFFFFC300, 0xFFF17E01, 0xFFFFC300,
            0xFFF17E01, 0xFFFFC300, 0xFFF17E01};
    /**
     * 与文字对应的图片
     */
    private int[] mResourceIds = new int[]{R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher};

    /**
     * 与文字对应图片的bitmap数组
     */
    private Bitmap[] mBitmap;

    /**
     * 盘块的个数
     */
    private int mItemCount = 6;

    /**
     * 绘制盘块的范围
     */
    private RectF mRange = new RectF();

    /**
     * 圆的直径
     */
    private int mRadius;

    /**
     * 绘制盘快的画笔
     */
    private Paint mArcPaint;

    /**
     * 绘制文字的画笔
     */
    private Paint mTextPaint;
    /**
     * 滚动的速度
     */
    private double mSpeed;
    /**
     * 起始角度
     */
    private volatile float mStartAngle = 0;

    /**
     * 圆弧角度
     */
    private float mSweepAngle;

    /**
     * 画文字的 path
     */
    private Path mTextPath;

    /**
     * 文字的大小
     */
    private float mTextSize = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());

    public TurnTableSurfaceView(Context context) {
        this(context, null);
    }

    public TurnTableSurfaceView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TurnTableSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mHolder = getHolder();
        mHolder.addCallback(this);

        // setZOrderOnTop(true);// 设置画布 背景透明
        // mHolder.setFormat(PixelFormat.TRANSLUCENT);

        //设置可获得焦点
        setFocusable(true);
        setFocusableInTouchMode(true);
        //设置常亮
        this.setKeepScreenOn(true);

        // 初始化绘制圆弧的画笔
        mArcPaint = new Paint();
        mArcPaint.setAntiAlias(true);
        mArcPaint.setDither(true);

        // 初始化绘制文字的画笔
        mTextPaint = new Paint();
        mTextPaint.setColor(0xffffffff);
        mTextPaint.setTextSize(mTextSize);

        mSweepAngle = 360 / mItemCount;

        mTextPath = new Path();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        int min = Math.min(w,h) - getPaddingLeft() - getPaddingRight();
        mRadius = min;
        mRange = new RectF(getPaddingLeft(),getPaddingTop(),mRadius +getPaddingLeft(),mRadius + getPaddingTop());

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        //开启线程
        mIsRunning = true;
        mThread = new Thread(runnable);
        mThread.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        //通知关闭线程
        mIsRunning = false;
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            while (mIsRunning) {
                long start = System.currentTimeMillis();
                draw();
                long end = System.currentTimeMillis();
                try
                {
                    if (end - start < 50)
                    {
                        Thread.sleep(50 - (end - start));
                    }
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }
    };

    private void draw() {
        try {
            mCanvas = mHolder.lockCanvas();
            if (mCanvas != null) {
                drawArc(mCanvas);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mCanvas != null) {
                mHolder.unlockCanvasAndPost(mCanvas);
            }
//            clearDraw();
        }
    }

    private void drawArc(Canvas canvas){
        for(int i = 0;i<mItemCount;i++){
            mArcPaint.setColor(mColors[i]);
            canvas.drawArc(mRange,mStartAngle,mSweepAngle,true,mArcPaint);
            drawText(canvas,mStartAngle,mSweepAngle,mText[i]);
            mStartAngle += mSweepAngle;
        }
        mStartAngle += 30;

    }

    private void drawText(Canvas canvas,float startAngle,float sweepAngle,String string){
        mTextPath.addArc(mRange,startAngle,sweepAngle);
        float textWidth = mTextPaint.measureText(string);
        float hOffset = (float) (Math.PI * mRadius / mItemCount /2 - textWidth/2);
        float vOffset = mRadius / 2 / 6;
        canvas.drawTextOnPath(string,mTextPath,hOffset,vOffset,mTextPaint);
        mTextPath.reset();
        Log.i("test","onDraw");
    }

//    private Handler mHandler = new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            draw();
//            mStartAngle = mStartAngle + 6;
//            doRotate();
//        }
//    };
//
//    private void doRotate(){
//        mHandler.sendEmptyMessageDelayed(1,1000);
//    }
//
//    public void clearDraw() {
//        Canvas canvas = null;
//        try {
//            canvas = mHolder.lockCanvas(null);
//            canvas.drawColor(Color.BLACK);
//        }catch (Exception e) {
//            // TODO: handle exception
//        }finally {
//            if(canvas != null) {
//                mHolder.unlockCanvasAndPost(canvas);
//            }
//        }
//    }



}
